package top.yj95.kecwv.util;

import static java.util.stream.Collectors.*;

import java.lang.ProcessHandle.Info;
import java.util.List;

import top.yj95.kecwv.consts.ProcNames;

/**
 * 进程工具类
 * @author 杨军
 * @since 2025-07-10
 */
public class ProcUtils {
    
    private ProcUtils() {}
    
    /**
     * 查找 Eclipse 系列进程
     * @return 查找结果
     * @author 杨军
     * @since 2025-07-10
     */
    public static List<ProcessHandle> findEclipseSeries() {
        return ProcessHandle.allProcesses().filter(ProcUtils::isEclipseSeriesProc).collect(toList());
    }
    
    /**
     * 判断是否为 Eclipse 系列进程
     * @param proc 待判断的进程
     * @return 是 Eclipse 系列进程返回 <code>true</code>，否则返回 <code>false</code>
     * @author 杨军
     * @since 2025-07-10
     */
    public static boolean isEclipseSeriesProc(ProcessHandle proc) {
        Info info = proc.info();
        if (info.command().isEmpty()) {
            return false;
        }
        String command = info.command().get();
        String[] tokens = command.split("\\\\");
        String programName = null;
        if (null == tokens || tokens.length <= 0) {
            programName = command.toUpperCase();
        } else {
            programName = tokens[tokens.length - 1].toUpperCase();
        }
        for (String procName : ProcNames.ECLIPSE_SERIES) {
            if (programName.indexOf(procName) >= 0) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 判断是否为 WebView2 进程
     * @param proc 待判断的进程
     * @return 是 WebView2 进程返回 <code>true</code>，否则返回 <code>false</code>
     * @author 杨军
     * @since 2025-07-10
     */
    public static boolean isWebView2Proc(ProcessHandle proc) {
        Info info = proc.info();
        if (info.command().isEmpty()) {
            return false;
        }
        String command = info.command().get();
        String[] tokens = command.split("\\\\");
        String programName = null;
        if (null == tokens || tokens.length <= 0) {
            programName = command.toUpperCase();
        } else {
            programName = tokens[tokens.length - 1].toUpperCase();
        }
        return programName.indexOf(ProcNames.WEB_VIEW2) >= 0;
    }
    
}
